package cn.tedu.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <pre>
 *      创建一个拦截所有请求的过滤器.
 *      用web.xml来实现过滤器的配置
 * </pre>
 *
 * @author restyhap
 * @since 2019-11-04 16:40
 */
public class CharsetFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharsetFilter... init()... 过滤器启动");
       filterConfig.getInitParameter("char");

    }

    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //让所有的页面请求与响应的编码格式都是UTF-8
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8");
        response.setCharacterEncoding("utf-8");

        filterChain.doFilter(request,response);//往下放行.可以交由其余Filter或Servlet请求.
        System.out.println("CharsetFilter...   doFilter()... 字符集编码设置成了UTF-8");
    }

    @Override
    public void destroy() {
        System.out.println("CharsetFilter... destroy()... 过滤器销毁");
    }
}
